package com.landray.kmss.yggs.todonotify;

import lombok.extern.slf4j.Slf4j;
import org.apache.cxf.binding.soap.SoapHeader;
import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.binding.soap.interceptor.AbstractSoapInterceptor;
import org.apache.cxf.headers.Header;
import org.apache.cxf.helpers.DOMUtils;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.Phase;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.xml.namespace.QName;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;

/**
 * 消息拦截器，在报文中添加消息头，以支持服务端的验证
 *
 */
@Slf4j
public class AddSoapHeader extends AbstractSoapInterceptor {

	public AddSoapHeader() {
		super(Phase.WRITE);
	}

	/**
	 * 处理消息，添加消息头
	 *
	 * @param message SOAP消息
	 * @throws Exception
	 */
	public void handleMessage(SoapMessage message) throws Fault {
		WebServiceConfig cfg = WebServiceConfig.getInstance();
		Document doc = DOMUtils.createDocument();

		// 添加用户名信息
		Element userElement = doc.createElement("tns:user");
		userElement.setTextContent(cfg.getUser());

		// 添加密码信息
		Element pwdElement = doc.createElement("tns:password");
		try {
			pwdElement.setTextContent(new BigInteger(1, MessageDigest.getInstance("md5").digest(cfg.getPassword().getBytes())).toString(16));
		} catch (NoSuchAlgorithmException e) {
			log.error(e.getMessage(), e);
		}

		// 创建消息头节点
		Element root = doc.createElementNS("http://sys.webservice.client"
		    , "tns:RequestSOAPHeader");
		root.appendChild(userElement);
		root.appendChild(pwdElement);

		QName qname = new QName("RequestSOAPHeader");
		SoapHeader head = new SoapHeader(qname, root);
		List<Header> headers = message.getHeaders();
		headers.add(head);
	}

}
